package top.lingkang.fas.admin.config;

import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.dao.SaTokenDaoForRedisson;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.solon.integration.SaTokenInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Context;
import org.redisson.api.RedissonClient;
import top.lingkang.fas.common.dto.R;
import top.lingkang.fas.common.http.HttpStatus;

/**
 * @author lingkang
 * created by 2025/7/19 23:55
 */
@Slf4j
@Configuration
public class SecurityConfig extends SaTokenInterceptor {

    private static final String notLogin = R.fail(HttpStatus.UNAUTHORIZED, "您还未登录").toJson();
    private static final String json500 = R.fail(HttpStatus.ERROR, "发生未知错误").toJson();
    private static final String notPermission = R.fail(HttpStatus.FORBIDDEN, "权限不足").toJson();

    // redis 存储session
    @Bean
    public SaTokenDao saTokenDaoInit(@Inject RedissonClient redissonClient) {
        return new SaTokenDaoForRedisson(redissonClient);
    }

    public SecurityConfig() {
        log.info("开始加载sa-token安全机制");
        // 指定 [拦截路由] 与 [放行路由]
        addInclude("/**");// 拦截路由
        addExclude(// 不鉴权的请求    放行路由
                "/favicon.ico",
                "/login", "/register", "/captchaImage",
                "/", "/page/**", "/assets/**"
        );

        // 认证函数: 每次请求执行
        setAuth(req -> {
            // System.out.println("---------- sa全局认证");
            SaRouter.match("/**", StpUtil::checkLogin);
        });
        setError(e -> {
            Context current = Context.current();
            current.contentType("application/json; charset=utf-8");
            if (e instanceof NotLoginException) {
                if (((NotLoginException) e).getCode() == 11014) {// 被顶号
                    StpUtil.logout();
                    return notLogin;
                }
                current.status(HttpStatus.UNAUTHORIZED);
                return notLogin;
            }
            if (e instanceof NotPermissionException) {
                log.debug("权限不足 {}", e.getMessage());
                return notPermission;
            }
            log.error("鉴权错 {}", e.getMessage(), e);
            return json500;
        });
    }

}
